import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author WGG
 * @create 2023-08-20 21:29
 */
public class Test03 {

    static ReentrantLock lock = new ReentrantLock();
    static Condition condition = lock.newCondition();

    public static void main(String[] args) {
        Thread thread = new Thread(
                () -> {
                    lock.lock();
                    System.out.println("线程A 拿到锁");
                    try {
                        Thread.sleep(5000);
                        System.out.println("线程A 释放锁，挂起线程");
                        condition.await(); // 线程A等待
                        System.out.println("线程A 被唤醒，继续执行");
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt(); // 重新中断线程
                        System.err.println("线程A 被中断");
                    } finally {
                        lock.unlock(); // 确保释放锁
                    }
                }
                , "线程A");
        thread.start();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        lock.lock();
        System.out.println("main 拿到锁");
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            condition.signal(); // 唤醒等待的线程A
            System.out.println("main 释放锁");
            lock.unlock(); // 释放锁
        }

        // 创建新的线程对象来重新启动线程A
        Thread threadA = new Thread(
                () -> {
                    lock.lock();
                    System.out.println("线程A 拿到锁");
                    try {
                        Thread.sleep(5000);
                        System.out.println("线程A 释放锁，挂起线程");
                        condition.await(); // 线程A等待
                        System.out.println("线程A 被唤醒，继续执行");
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt(); // 重新中断线程
                        System.err.println("线程A 被中断");
                    } finally {
                        lock.unlock(); // 确保释放锁
                    }
                }
                , "线程A");
        threadA.start();
    }
}
